#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
安装脚本 - 自动安装依赖并检查环境

作者: AI Assistant
版本: 1.0.0
"""

import sys
import subprocess
import os
from pathlib import Path


def check_python_version():
    """检查Python版本"""
    print("检查Python版本...")
    if sys.version_info < (3, 7):
        print("❌ 错误: 此程序需要Python 3.7或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    else:
        print(f"✅ Python版本检查通过: {sys.version}")
        return True


def install_requirements():
    """安装依赖包"""
    requirements_file = Path(__file__).parent / "requirements.txt"
    
    if not requirements_file.exists():
        print("❌ 错误: 未找到requirements.txt文件")
        return False
    
    print("开始安装依赖包...")
    try:
        # 升级pip
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        
        # 安装依赖
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", str(requirements_file)])
        print("✅ 依赖包安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装依赖包失败: {e}")
        return False


def check_installation():
    """检查安装是否成功"""
    print("检查安装结果...")
    
    required_packages = {
        'requests': 'requests',
        'GitPython': 'git',
        'pillow': 'PIL',
        'ttkbootstrap': 'ttkbootstrap'
    }
    
    failed_packages = []
    
    for package_name, import_name in required_packages.items():
        try:
            __import__(import_name)
            print(f"✅ {package_name} 安装成功")
        except ImportError:
            print(f"❌ {package_name} 安装失败")
            failed_packages.append(package_name)
    
    if failed_packages:
        print(f"\n❌ 以下包安装失败: {', '.join(failed_packages)}")
        print("请手动安装: pip install " + " ".join(failed_packages))
        return False
    else:
        print("\n✅ 所有依赖包安装成功！")
        return True


def create_shortcut():
    """创建启动快捷方式"""
    print("创建启动脚本...")
    
    project_root = Path(__file__).parent
    
    if os.name == 'nt':  # Windows
        batch_content = f'''@echo off
cd /d "{project_root}"
python main.py
pause
'''
        with open(project_root / "启动工具.bat", "w", encoding="gbk") as f:
            f.write(batch_content)
        print("✅ 创建了启动工具.bat")
    
    else:  # Unix-like
        shell_content = f'''#!/bin/bash
cd "{project_root}"
python3 main.py
'''
        script_path = project_root / "启动工具.sh"
        with open(script_path, "w", encoding="utf-8") as f:
            f.write(shell_content)
        os.chmod(script_path, 0o755)
        print("✅ 创建了启动工具.sh")


def main():
    """主函数"""
    print("=" * 50)
    print("Gitee仓库批量管理工具 - 自动安装脚本")
    print("=" * 50)
    
    success = True
    
    # 检查Python版本
    if not check_python_version():
        success = False
    
    # 安装依赖
    if success and not install_requirements():
        success = False
    
    # 检查安装
    if success and not check_installation():
        success = False
    
    # 创建快捷方式
    if success:
        create_shortcut()
        print("\n🎉 安装完成！")
        print("\n使用方法:")
        print("1. 直接运行: python main.py")
        if os.name == 'nt':
            print("2. 双击运行: 启动工具.bat")
        else:
            print("2. 执行脚本: ./启动工具.sh")
        print("\n请确保已获取Gitee的Access Token后再使用。")
        print("获取方法请参考README.md文件。")
    else:
        print("\n❌ 安装过程中出现错误，请检查并重试。")
        return 1
    
    return 0


if __name__ == "__main__":
    exit_code = main()
    input("\n按Enter键退出...")
    sys.exit(exit_code)
